package com.mylogistics.common.service.impl;

import com.mylogistics.common.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * 验证码服务类
 */
@Service
public class EmailCodeServiceImpl implements CodeService {

    @Autowired
    public JavaMailSender emailSender;

    @Autowired
    CodeCacheService codeCacheService;

    @Value("${spring.mail.username}")
    String from;
    //发送简单消息
    public void sendSimpleMessage(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to); //收件人地址
        message.setFrom(from); //发件人地址
        message.setSubject(subject);//发送的主题
        message.setText(text);//发送的内容
        emailSender.send(message);//发送信息
    }
    static String[] codes ={"0","1","2","3","4","5","6","7","8","9"};
    public static String getRandomCode(int maxNum){
        Random random = new Random();
        random.setSeed(System.currentTimeMillis());
        StringBuffer code = new StringBuffer();

        for (int i=0;i<maxNum;i++){
            code.append(codes[Math.abs(random.nextInt())%codes.length]);
        }
        return code.toString();
    }
    @Override
    public Object createAndSendCode(Object principal) {
        //创建并且发送验证码
        //获取验证码
        String code = getRandomCode(6);
        //发送验证码
        sendSimpleMessage((String)principal,"验证码",code);

        //将验证码进行缓存
        codeCacheService.saveCode(principal,code);

        return code;
    }
    //验证代码
    @Override
    public boolean verifyCode(Object principal, Object code) {

        String targetCode = (String) codeCacheService.getCode(principal);

        if(((String)code).equals(targetCode)){
            codeCacheService.deleteCode(principal);
            return true;
        }
        return false;
    }
}
